<template>
  <el-card>
    <div slot="header">
      <h3>集团指导加价率-新增</h3>
    </div>
    <div>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput required :reason.sync="launchReason" />
      <el-divider />
      <skus-table
        ref="skusTable"
        :tableHeight="480"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        @handleCancelSelect="handleDelete"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </div>
    <LinkCateBrandDialog
      :visible.sync="dialogVisible.linkCateBrand"
      :confirmSubmit="setTableData"
    />
    <BatchSetRateDialog
      :visible.sync="dialogVisible.batchSetRate"
      @getRates="updateTableRates"
    />
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import LinkCateBrandDialog from '@/components/LinkCateBrandDialog';
import BatchSetRateDialog from '@/components/BatchSetRateDialog';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { TableInfo, openConfirmError, openConfirmTips } from '@/utils/getUtils';
import { createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import { TABLE_COLUMNS } from './constants/add';
import { OPE_TYPES, COMMIT_TYPES, getMessageColumns } from '@/constants/markupRate';
import {
  importProductMarkupRateTemplateUrl,
  exportProductMarkupRateTemplateService,
  commitProductMarkupRateRecordService,
  refreshProductMarkupRateListService
} from '@/api/basics/categoryManage/guideMarkupRate';
export default {
  components: {
    BtnRender,
    SkusTable,
    LaunchReasonInput,
    LinkCateBrandDialog,
    BatchSetRateDialog
  },
  data () {
    return {
      launchReason: '', // 发起原因
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      btnLoading: {
        export: false, // 导出按钮loading
        submit: false, // 提交按钮loading
      },
      dialogVisible: {
        linkCateBrand: false,
        batchSetRate: false
      },
      isIgnoreTipMsg: false,
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const linkCateBrandBtn = { label: '关联品类品牌', method: this.handleLinkCateBrand }
      const batchMarkupRateBtn = {
        label: '批量加价率',
        method: this.handleBatchMarkupRate,
        disabled: this.TableInfo.isNullList()
      }
      const exportTempBtn = {
        label: '导出模板',
        method: this.handleExportTemplate,
        disabled: this.TableInfo.isNullList(),
        loading: this.btnLoading.export
      }
      const importBtn = {
        label: '导入',
        action: importProductMarkupRateTemplateUrl,
        methods: { handleUploadSuccess: this.handleUploadSuccess },
        isImport: true,
        loadingFn: this.TableInfo.setLoading,
        data: { commitType: COMMIT_TYPES.Group }
      }
      const submitBtn = {
        label: '提交',
        method: this.handleSubmit,
        disabled: this.TableInfo.isNullList(),
        loading: this.btnLoading.submit
      }
      const clearAllBtn = {
        label: '清空表格数据',
        method: this.handleClearTableData,
        disabled: this.TableInfo.isNullList(),
        type: 'default'
      }
      const gobackBtn = { label: '返回', method: this.handleGoBack, type: 'default' }
      const btnBars = [gobackBtn, clearAllBtn, linkCateBrandBtn, batchMarkupRateBtn, exportTempBtn, importBtn, submitBtn]
      return getListPageBtnsBar(h, btnBars, this.showBtn, 'end')
    },
    // 删除
    handleDelete ({ row }) {
      const filterList = this.TableInfo.list.filter(
        item => this.getDimensionKey(item) != this.getDimensionKey(row)
      )
      this.TableInfo.setList(filterList)
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'guideMarkupRateList' })
    },
    // 清空表格数据
    handleClearTableData () {
      const content = '确定后将清空所有已关联数据，您确认吗？'
      this.$confirm(content, '清空', {
        type: 'warning',
      }).then(() => {
        this.TableInfo.clearList()
      }).catch(() => {})
    },
    // 关联品类品牌
    handleLinkCateBrand () {
      this.dialogVisible.linkCateBrand = true
    },
    // 批量加价率
    handleBatchMarkupRate () {
      this.dialogVisible.batchSetRate = true
    },
    // 导出模板
    async handleExportTemplate () {
      const uuid = generateUuid()
      const data = {
        categoryBrandSeries: this.getCategoryBrandSeries(this.TableInfo.list),
        uuid
      }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportProductMarkupRateTemplateService(data, loadingFn)
      createExcelByExport({ excelTitle: `新增集团指导加价率_${uuid}`, res })
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.TableInfo.setList(res?.retData)
      }
    },
    // 提交
    async handleSubmit (isIgnoreTipMsg = false) {
      if (!this.launchReason) return this.$message.warning('发起原因不能为空')
      const data = {
        commitProductMarkupRateRecordDetailParams: this.TableInfo.list,
        isIgnoreTipMsg, // 是否忽略异常范围提示（点击提交不忽略，页面存在有异常范围的需业务确认，点击仍要提交时候可忽略直接生成单据）
        opeType: OPE_TYPES.Add,
        commitType: COMMIT_TYPES.Group,
        launchReason: this.launchReason
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitProductMarkupRateRecordService(data, loadingFn)
      if (res?.retData) this.executeSubmitedTask(res.retData)
    },
    // 执行提交后的回调任务
    executeSubmitedTask (retData) {
      const processSetInfo = () => {
        this.TableInfo.setColumns([...getMessageColumns(retData), ...TABLE_COLUMNS])
        this.TableInfo.setList(retData.commitProductMarkupRateRecordDetailVos)
      }
      const processTipSubmit = () => { this.handleSubmit(true) } // 仍要提交执行回调
      if (retData.hasErrorData) return openConfirmError(processSetInfo) // 提交有错误
      if (retData.hasTipMsg) return openConfirmTips(processTipSubmit, processSetInfo) // 提交有异常
      // 提交成功
      this.$message.success('提交成功')
      this.handleGoBack()
    },
    // 设置表格数据
    async setTableData ({ results, loadingFn, cancelFn }) {
      const data = {
        categoryBrandSeries: this.getCategoryBrandSeries(results),
        uuid: generateUuid(),
        commitType: COMMIT_TYPES.Group
      }
      const res = await refreshProductMarkupRateListService(data, loadingFn)
      if (res?.retData) {
        cancelFn()
        this.TableInfo.setList(res.retData)
      }
    },
    // 更新表格所有加价率
    updateTableRates (rates) {
      const newList = this.TableInfo.list.map(item => ({ ...item, ...rates }))
      this.TableInfo.setList(newList)
    },
    // 获取品类品牌系列uuid集合
    getCategoryBrandSeries (list) {
      const categoryBrandSeries = list.map(item => this.getDimensionKey(item))
      return categoryBrandSeries
    },
    // 获取唯一标识key值
    getDimensionKey (row) {
      const idVal = `${row.categoryUuid}_${row.brandUuid}_${row.seriesUuid}`
      return idVal
    }
  }
}
</script>
